#!/usr/bin/env python3
"""
Version Update Script
版本更新脚本 - 用于更新项目版本号

Usage:
    python scripts/update_version.py <new_version>
    
Example:
    python scripts/update_version.py 1.1.0
"""

import re
import sys
import argparse
from pathlib import Path
from typing import List, Tuple


def update_file_version(file_path: Path, version_pattern: str, new_version: str) -> bool:
    """更新文件中的版本号"""
    try:
        content = file_path.read_text(encoding='utf-8')
        
        # 使用正则表达式替换版本号
        new_content = re.sub(version_pattern, new_version, content)
        
        if new_content != content:
            file_path.write_text(new_content, encoding='utf-8')
            print(f"✅ 更新 {file_path.name}: {new_version}")
            return True
        else:
            print(f"ℹ️  {file_path.name}: 无需更新")
            return False
            
    except Exception as e:
        print(f"❌ 更新 {file_path.name} 失败: {e}")
        return False


def main():
    parser = argparse.ArgumentParser(description='更新项目版本号')
    parser.add_argument('version', help='新版本号 (例如: 1.1.0)')
    parser.add_argument('--dry-run', action='store_true', help='试运行，不实际修改文件')
    
    args = parser.parse_args()
    
    new_version = args.version
    
    # 验证版本号格式
    if not re.match(r'^\d+\.\d+\.\d+(?:[a-zA-Z0-9.-]+)?$', new_version):
        print(f"❌ 无效的版本号格式: {new_version}")
        print("支持的格式: X.Y.Z 或 X.Y.Z-suffix")
        sys.exit(1)
    
    print(f"🔄 开始更新版本号到: {new_version}")
    
    # 项目根目录
    project_root = Path(__file__).parent.parent
    
    # 需要更新的文件列表
    files_to_update: List[Tuple[Path, str, str]] = [
        # (文件路径, 搜索模式, 替换模式)
        (
            project_root / "src" / "media_create" / "core" / "config.py",
            r'(app_version: str = Field\(default=")[^"]*("[^)]*\))',
            f'\\1{new_version}\\2'
        ),
        (
            project_root / "pyproject.toml",
            r'(version = ")[^"]*("\s*$)',
            f'\\1{new_version}\\2'
        ),
        (
            project_root / "CHANGELOG.md",
            r'(## \[)[^\]]*(\] - \d{4}-\d{2}-\d{2})',
            f'\\1{new_version}\\2'
        ),
        (
            project_root / "README.md",
            r'(version-)[^-\]]*(-blue\.svg)',
            f'\\1{new_version}\\2'
        ),
        (
            project_root / "scripts" / "demo.py",
            r'(app_version = ")[^"]*("\s*$)',
            f'\\1{new_version}\\2'
        ),
    ]
    
    updated_files = []
    
    for file_path, search_pattern, replace_pattern in files_to_update:
        if not file_path.exists():
            print(f"⚠️  文件不存在: {file_path}")
            continue
            
        if args.dry_run:
            print(f"🔍 将更新: {file_path.name}")
            updated_files.append(str(file_path))
        else:
            # 执行实际的正则表达式替换
            try:
                content = file_path.read_text(encoding='utf-8')
                new_content = re.sub(search_pattern, replace_pattern, content, flags=re.MULTILINE)
                
                if new_content != content:
                    file_path.write_text(new_content, encoding='utf-8')
                    print(f"✅ 更新 {file_path.name}: {new_version}")
                    updated_files.append(str(file_path))
                else:
                    print(f"ℹ️  {file_path.name}: 无需更新")
            except Exception as e:
                print(f"❌ 更新 {file_path.name} 失败: {e}")
    
    if args.dry_run:
        print(f"\n🔍 试运行完成，将更新以下文件:")
        for file_path in updated_files:
            print(f"  - {file_path}")
    else:
        print(f"\n✅ 版本更新完成！")
        print(f"📊 更新了 {len(updated_files)} 个文件")
        
        if updated_files:
            print("\n📁 更新的文件:")
            for file_path in updated_files:
                print(f"  - {file_path}")
        
        print(f"\n📝 下一步操作:")
        print(f"  1. 检查更新后的文件")
        print(f"  2. 运行测试确保一切正常")
        print(f"  3. 提交更改并创建发布")
        print(f"  4. 更新 CHANGELOG.md 中的发布说明")


if __name__ == "__main__":
    main()
